package models;

import java.util.Queue;

/**
 * Created by IntelliJ IDEA.
 * User: Julioagh
 * Date: 08/11/11
 * Time: 11:56 PM
 * To change this template use File | Settings | File Templates.
 */
public class LowerValueFounder {

    public static int findNextPosition(int initPoint, int[][] routeMatrix, Queue<RoutePoint> optimizedRoute) {
        int minPosition = Integer.MAX_VALUE;
        int minValue = Integer.MAX_VALUE;
        for (int col = 0; col < routeMatrix.length; col++) {
            int value = routeMatrix[initPoint][col];
            if (isValidMinValue(minValue, value, col, optimizedRoute)) {
                minPosition = col;
                minValue = value;
            }
        }
        for (int row = 0; row < routeMatrix.length; row++) {
            int value = routeMatrix[row][initPoint];
            if (isValidMinValue(minValue, value, row, optimizedRoute)) {
                minPosition = row;
                minValue = value;
            }
        }
        return minPosition;
    }

    private static boolean isValidMinValue(int minimaDistancia, int distancia, int index, Queue<RoutePoint> optimizedRoute) {
        return distancia != 0 && distancia <= minimaDistancia && !optimizedRoute.contains(RouteMapper.getRoutePoint(index));
    }

    public static void findRoute(int initPoint, int[][] routeMatrix, Queue<RoutePoint> optimizedRoute) {
        if (optimizedRoute.size() == routeMatrix.length) return;
        int nexPosition = findNextPosition(initPoint, routeMatrix, optimizedRoute);
        if (!optimizedRoute.contains(RouteMapper.getRoutePoint(nexPosition)))
            optimizedRoute.add(RouteMapper.getRoutePoint(nexPosition));
        findRoute(nexPosition, routeMatrix, optimizedRoute);
    }
}
